import config from '../config/index.js'

// 超时时间（请求）
const timeout = 10 * 1000

// 接口地址
const baseUrl = config.url;

// 接口对象
const api = {};

/* 
	定义接口方法
	name 方法名 例如：$api.name 请求接口
	desc 描述接口
	url 接口路径
	usedLoading:是否使用loading加载提示框，默认true
	method 请求方式 空值为get
	参考接口文档：https://binaryify.github.io/NeteaseCloudMusicApi/
 */
const apiList=[
	{
		desc: '默认搜索关键词',
		name: 'searchDefault',
		url: '/search/default'
	},
	{
		desc: '轮播图数据',
		name: 'banner',
		url: '/banner'
	},
	{
		desc: '歌单( 网友精选碟 )',
		name: 'topPlaylist',
		url: '/top/playlist'
	},
	{
		desc: '手机登录',
		name: 'loginCellphone',
		url: '/login/cellphone'
	},
	{
		desc: '获取用户播放记录',
		name: 'userRecord',
		url: '/user/record'
	},
	{
		desc: '推荐歌单',
		name: 'personalized',
		url: '/personalized'
	},
	{
		desc: '所有榜单',
		name: 'toplist',
		url: '/toplist',
		usedLoading: false
	},
	{
		desc: '获取歌单详情',
		name: 'playlistDetail',
		url: '/playlist/detail',
		usedLoading: false
	},
	{
		desc: '获取音乐 url',
		name: 'songUrl',
		url: '/song/url',
		usedLoading: true
	},
	{
		desc: '获取歌词',
		name: 'lyric',
		url: '/lyric',
		usedLoading: true
	},
	{
		desc: '热搜列表(详细)',
		name: 'searchHotDetail',
		url: '/search/hot/detail',
		usedLoading: false
	},
	{
		desc: '搜索建议',
		name: 'searchSuggest',
		url: '/search/suggest',
		usedLoading: false
	},
	{
		desc: '搜索多重匹配',
		name: 'searchMultimatch',
		url: '/search/multimatch',
		usedLoading: true
	},
	{
		desc: '搜索',
		name: 'search',
		url: '/search',
		usedLoading: true
	},
	{
		desc: '搜索 (更全)',
		name: 'cloudsearch',
		url: '/cloudsearch',
		usedLoading: true
	},
	
];

/* 遍历接口 */
apiList.forEach(item => {
	api[item.name] = function(params){
		let {data, header, dataType} = params || {};
		
		return new Promise((resolve, reject)=> {
			try{
				if(false !== item.usedLoading){
					uni.showLoading({
						title: 'loading...'
					});
				}
				
				uni.request({
					url: baseUrl + item.url,
					method: item.method || "GET",
					data: data,
					header: header,
					dataType: dataType || "json",
					timeout: timeout,
					success:(res) => {
						if(res.data != null  && res.data.hasOwnProperty('code') && res.data.code === 200) {
							resolve(parseSuccessResponseData(res));							
						}else {
							resolve(parseFailResponseData(res));
						}
					},
					fail: (e)=>{
						console.error("错误url:" + item.url);
						reject(parseFailResponseData(e));
					},
					complete: () => {
						if(false !== item.usedLoading){
							uni.hideLoading();
						}
					}
				});
			}catch (e) {
				console.error("异常："+ e);
				reject({
					message: "请求错误",
				});
				showToast("请求错误");
			}
		});
	}
});

/* 
	防止返回的格式不一致  
 */
function parseSuccessResponseData(res){
	return res.data || res.result
}

/* 
	请求状态错误时
 */
function parseFailResponseData(e){
	if(e.errMsg){
		showToast(e.errMsg)
	}
	return e;
}

/* 显示提示 */
function showToast(message){
	uni.showToast({
		title: message,
		duration: 1500,
		icon: "none"
	});
}

export default api;